﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using Microsoft.Xna.Framework;
using WindowsGame.GameObjects;
using WindowsGame.Library.ProxyObjects;

namespace WindowsGame.Components
{
	public abstract class BaseGameComponent
	{
		private GameObject owner;
		private ProxyComponent proxyComponent;

		public virtual void Initialize(GameObject owner, ProxyComponent proxyComponent)
		{
			this.owner = owner;
			this.proxyComponent = proxyComponent;

			LoadProperties();
		}

		public virtual void LoadContent()
		{
		}

		public Int32 ID { get; set; }
		public GameObject Owner { get { return owner; } }

		private void LoadProperties()
		{
			PropertyInfo[] properties = this.GetType().GetProperties();
			foreach (PropertyInfo property in properties)
			{
				String key = property.Name.ToLower();
				Object value;
				Boolean found = proxyComponent.Properties.TryGetValue(key, out value);

				if (!found)
				{
					continue;
				}

				Type type = property.PropertyType;
				value = GetValue(value, type);

				property.SetValue(this, value, null);
			}
		}

		private Object GetValue(Object value, Type type)
		{
			String text = ((String)value).Trim();
			if (type == typeof(Vector3))
			{
				Char[] delim = new [] { ','};
				String[] array = text.Split(delim);

				Single x = Single.Parse(array[0]);
				Single y = Single.Parse(array[1]);
				Single z = Single.Parse(array[2]);
				value = new Vector3(x, y, z);
			}
			else if (type.BaseType == typeof(System.Enum))
			{
				value = Enum.Parse(type, text, true);
			}
			else
			{
				value = Convert.ChangeType(value, type, CultureInfo.InvariantCulture);
			}
			
			return value;
		}
	}
}